//
//  CalcViewModel.swift
//  CrseAsst
//
//  Created by 申铭 on 2024/3/5.
//

import Foundation
import SwiftUI

final class CalcViewModel: ObservableObject {
    @Published var countTips: String = ""
    @Published var answerText: String = ""
    @Published var ques: String = ""
    @Published var showResult: Bool = false
    @Published var isRight: Bool = false
    
    private var currentIndex: Int = 0
    
    private let genQues = GenerateQuestions()
    private var type: CalcType = .twoDigitAdd
    
    private var questions = [BaseQuestion]()
//    private let questions = GenerateQuestions().generateQues(type: .twoDigitAdd)
    
    /// 设置类型并显示第一个题目
    /// - Parameter type: 类型
    func setType(_ type: CalcType) {
        self.type = type
        self.questions = genQues.generateQues(type: type)
        
        ques = questions[currentIndex].getTopicDesc()
        showCountTips()
    }
    
    /// 下一题
    func next() {
        let theQues = questions[currentIndex]
        
        // 统计数量
        if !answerText.isEmpty {
//            let key = Field.Statistics.doneTotalNumber.rawValue
//            var num = (Int)(KeyValueStore.get(key) ?? "0") ?? 0
//            num = num + 1
//            KeyValueStore.set(key: key, value: "\(num)")
        }
        
//        if type == .decimal2Fraction {
//            let text = answerText ?? "1"
//            if text.contains(kDecimal2FractionSymbol) {
//                let arr = text.components(separatedBy: kDecimal2FractionSymbol)
//                let denominator = Float(arr[0]) ?? 1
//                let numerator = Float(arr[1]) ?? 0.0
//                topic.setInputAnswer(answer: nil, numerator: numerator, denominator: denominator)
//            }
//        } else if type == .base {
//            let text = answerText ?? "1"
//            let denominator = Float(text) ?? 0.0
//            topic.setInputAnswer(answer: nil, numerator: 0.0, denominator: denominator)
//        } else {
//            topic.setInputAnswer(answer: answerText)
//        }
        
        theQues.inputAnswer(answerText)
        
        currentIndex = currentIndex + 1
        
        ques = questions[currentIndex].getTopicDesc()
        showCountTips()
        
        answerText = "" // 清除数据
        showResult = true
        FDelay(1) {
            self.showResult = false
        }
        isRight = theQues.checkAnswer()
//
//        // 结束计算，跳转结果页
//        if currentIndex == topics.count - 1 {
//            jumpPage()
//            return
//        }
//        
        
//        setTopic()
    }
    
    /// 显示进度数量
    private func showCountTips() {
        countTips = "\(currentIndex + 1)/\(questions.count)"
    }
}
